import Vue from 'vue'
import Router from 'vue-router'
import store from '@/vuex/store'
import dicts from '@/utils/dicts'
Vue.use(Router)

// 总览
import { all } from '@/router/all'
// 云贷
import { loans } from '@/router/loans'
// 收藏
import { collect } from '@/router/collect'
// 合并 -- 路由
let routes = all.concat(loans, collect)

const router = new Router({
	routes
})

router.beforeEach((to, from, next) => {   	
  	// 重置 orgId 、quotaType
  	store.commit('orgId', '')
  	store.commit('nowTitle', {name:'', quotaType: ''})
  	store.commit('update', '')   
  	store.commit('period', {name: '', val:''}) 	
  	next();  

  	//数据监测-业务访问习惯
  	let nowTime = (new Date()).Format("yyyy-MM-dd hh:mm:ss")
  	let time = store.getters.time
	if(time) {
	  	let themeCode
	  	switch (from.meta.parent) {
	  		case 'collect': 
		  		themeCode = 0
		  		break
		  	case 'loans': 
		  		themeCode = 1
		  		break	  	
		  	case 'all': 
		  		themeCode = 0
		  		break	
	  	}

	  	let _busi = {
			'themeCode':  themeCode,
			'router': from.path,
			'title': from.meta.title,
			'inTime': time,
			'outTime': nowTime
		}

	  	let busiList = localStorage.getItem('busiList') 
	  	busiList = busiList ? JSON.parse(busiList) : {list: []}
	  	busiList.list.push(_busi)
	  	localStorage.setItem('busiList', JSON.stringify(busiList))  
  	} 
  	store.commit('time', nowTime)
});

router.afterEach((to, from, next) => {
	// 头部切换
	let headerData = {
		type : to.meta.type,
	}

	if(headerData.type == 'org') {  
		if(!store.getters.headerData.orgList) {		
			api.autoSelectedList().then(data => {
				let list = data.list;
				if(to.meta.parent == 'all') {
					headerData.title = '总览-' + list[0].orgName
				} else {
					headerData.title = to.meta.title
				}
				headerData.path = list[0].orgId				 
				headerData.orgList = [];
				list.map(item => {
					headerData.orgList.push({title: '总览-'+item.orgName, path: item.orgId})
				})
				headerData.menuList = dicts.dictRouter[to.meta.parent]
				store.commit('headerData', headerData)  
				store.commit('orgId', list[0].orgId)  
			}) 
		}
	}else if(headerData.type == 'router'){
		headerData.path = to.path
		headerData.title = to.meta.title
		headerData.menuList = dicts.dictRouter[to.meta.parent]
		store.commit('headerData', headerData)
	}else if(headerData.type == 'normal'){
		headerData.path = to.path
		headerData.title = to.meta.title
		headerData.menuList = dicts.dictRouter[to.meta.parent]
		store.commit('headerData', headerData)
	}
	window.scrollTo(0, 0)
});

export default router